

import React, { useState,useRef,useEffect,forwardRef,useImperativeHandle,useCallback } from 'react';
import { Message, Input, Button, Checkbox,Spin } from '@arco-design/web-react';
import { useLocation } from 'react-router-dom';
import { IconSafe, IconSearch, IconInfoCircle } from '@arco-design/web-react/icon';

import './Login.css'
import LoginIcon from '../../assets/logo.png'
import PhoneIcon from '../../assets/phone.svg'
import Qrcodelogin from '../../assets/qrcodelogin.png'
import Phonelogin from '../../assets/phonelogin.svg'
import useIntervalAsync from '../hook/useIntervalAsync'
import {login as ajaxLogin,sendCode,getWxQrcode,getWxLogin} from '../../api/all'
let pdf = {
  1:"/static/窄门用户服务协议V1.0.pdf",
  2:"/static/窄门隐私条款V1.0.pdf"
}
const LoginDialog = forwardRef((props, ref) => {

  const location = useLocation()

  const [showDialog,setShowDialog] = useState(false)
  const [phoneNumber,setPhoneNumber] = useState('')
  const [msgCode,setMsgCode] = useState('')  
  const [isAgree,setIsAgree] = useState(false) 
  const [mode,setMode] = useState(1) 
  const [qrcodeScene,setQrcodeScene] = useState(null)
  const [loading, setLoading] = useState(false);
  
  useImperativeHandle(ref, (props) => ({
    setShowDialog
  }));

  const [searchButton,setSearchButton] = useState(0)
  const countDownTimer = useRef(null);

  useEffect(() => {
    return () => {
      clearTimeout(countDownTimer.current);
    };
  }, []);

  useEffect(()=>{
      if(searchButton===0){
          clearInterval(countDownTimer.current)
      }
  },[searchButton])

  useEffect(()=>{
    if(mode===0){
      setLoading(true)
      getWxQrcode().then((res)=>{
        setQrcodeScene(res.result)
        setLoading(false)
      })
    }else{
      setQrcodeScene(null)
    }
  },[mode])



  const updateState = useCallback(async () => {
    if (qrcodeScene && qrcodeScene.url && mode===0 ) {
      const response = await getWxLogin({
        sence:qrcodeScene?.scene
      })
      if (response.code === 0) {
        update(0)
        setQrcodeScene(null)
        Message.success("登录成功");
        localStorage.setItem("token", response.result);
        if(location.pathname == '/login'){
          window.location=document.referrer;
        }else{
          window.location.reload(1)
        }
      }
    }
  }, [location.pathname, mode, qrcodeScene]);

  const update  =  useIntervalAsync(updateState, 3000);

  const openPdf = (e,event)=> {
    event.preventDefault();
    window.open(pdf[e])
  }

  const login = ()=> {
    if (phoneNumber === "") {
      Message.error("请输入手机号码");
      return;
    }
    if (msgCode === "") {
      Message.error("请输入验证码");
      return;
    }
    if (!isAgree) {
      Message.error("请勾选协议");
      return;
    }
    let params = {
      phone: phoneNumber,
      code: msgCode
    };
    ajaxLogin(params).then(res => {
      if (res.code === 0) {
        Message.success("登录成功");
        localStorage.setItem("token", res.result);
        if(location.pathname == '/login'){
          window.location=document.referrer;
        }else{
          window.location.reload(1)
        }
      }else{
        Message.error(res.message);
      }
    },error => {
        console.log("get request failed:",error);
    });
  }


  const getMsgCode = ()=> {
    if (phoneNumber === "") {
      Message.error("请输入手机号码");
      return;
    }
    if (phoneNumber.length !=11) {
      Message.error("请输入正确的手机号码");
      return;
    }
    let params = {
      phone: phoneNumber,
      type: "login"
    };
    sendCode(params).then(res => {
      if (res.code === 0) {
        countDown()
      }
    },error => {
        console.log("get request failed:",error);
    });
  }

  const countDown = (a,b)=>{
    setSearchButton(60)
    countDownTimer.current=setInterval(()=>{
      setSearchButton(c=>c-1)
    },1000)
  }

  return (
  <div style={{display:showDialog?'block':'none'}}>
    <div className="relative z-50" id="headlessui-dialog-:rdd:" role="dialog" aria-modal="true" data-headlessui-state="open"
      aria-labelledby="headlessui-dialog-title-:rdf:">
      <div className="fixed inset-0 newfixed" aria-hidden="true"></div>
      <div className="fixed inset-0 flex items-center justify-center max-h-screen m-5">
        <div style={{width:'480px',height:'520px',position:'relative'}} className="mx-auto rounded-3xl bg-primary-background shadow-2xl max-h-full overflow-hidden flex flex-col rounded-xl"
          id="headlessui-dialog-panel-:rde:" data-headlessui-state="open">
            {
              mode?<>
              <div className='login-info'>
              <div className='left'>
                <img className='login-img' alt='' src={LoginIcon}/>
                <p className='txt1'>想与所有大模型聊天？一个Chatalls就够了</p>
              </div>
              <div className='right'>
                <div className='input-box'>
                  <Input prefix={<img className='phoneIcon' alt='' src={PhoneIcon}/>} size='large' allowClear maxLength={11} height={46} placeholder='请输入手机号' value={phoneNumber} onChange={(value)=>{setPhoneNumber(value)}}/>
                  <div className='border'></div>
                  <Input
                    height={46}
                    prefix={<IconSafe />} 
                    addAfter={
                      <Button style={{width:'100px'}} onClick={getMsgCode} disabled={searchButton!=0} type='outline'>{searchButton || '获取验证码'}</Button>
                    }
                    allowClear
                    placeholder='验证码'
                    value={msgCode} onChange={(value)=>{setMsgCode(value)}}
                  />
                </div>
                    <Checkbox checked={isAgree} onChange={(value)=>{setIsAgree(value)}}>
                        我已阅读并同意  <span className='color-txt' onClick={(event)=>{openPdf(1,event)}}>用户协议</span> 与 <span className='color-txt' onClick={(event)=>{openPdf(2,event)}}>隐私政策</span>
                    </Checkbox>
                    <button onClick={()=>{login()}} type="button" className="login-btn">
                      登录
                    </button>
                    <div onClick={()=>{ Message.info('敬请期待')}} type="button" className="download-btn">
                    下载APP
                    </div>
              </div>
            </div><img className='qrcodelogin'  onClick={()=>{setMode(0)}} alt='' src={Qrcodelogin}/>
              </>:<>
              <div className='wxchat'>
                    <div className='tit'>
                    微信扫码 安全登录
                    </div>
                    <div className='qrcode-box'>
                    {!qrcodeScene?.url ? <Spin loading={loading}></Spin>:<img className='qrcode' src={qrcodeScene.url} alt='二维码'/>}
                    </div>
                    <div className='tips'>
                    请使用微信扫描二维码登录“Chatalls”
                    </div>
                    <div className='btn-box' onClick={()=>{setMode(1)}}>
                    手机号验证登录
                    </div>
              </div>
              <img className='qrcodelogin'  onClick={()=>{setMode(1)}} alt='' src={Phonelogin}/>
              </>
            }
        </div>
      </div>
    </div>
  </div>
  )
})

export default LoginDialog